package com.pay.sdk.usage;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.pay.sdk.R;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import sdk.pay.PayUtil;
import sdk.pay.listener.PayGetPayStatusListener;
import sdk.pay.listener.PayUtilCallBack;
import sdk.pay.model.PayTypeModel;
import sdk.pay.model.TokenParam;
import sdk.pay.utils.PayMD5Util;

public class SingleStepPayActivity extends Activity implements PayUtilCallBack {
    protected Dialog mProgressDialog;
    private RecyclerView mPayRecycleView;
    private TextView mPayName;
    private TextView mPayPrice;
    private Toast mToast;
    private PayUtil mPayUtil;
    private PayTypeRecycleAdapter mAdapter;
    private int mCheckedId = -1;
    private List<PayTypeModel> mPayTypeModelList;
    private GridSpacingItemDecoration mItemDecoration = new GridSpacingItemDecoration(2, 13, false);
    private String goodsName,goodsPrice;

    private static final String SYSTEM_NAME = PayActivity.SYSTEM_NAME;
    private static final String CODE = PayActivity.CODE;
    private static final String APPID = PayActivity.APPID;
    private static final String COM_KEY = PayActivity.COM_KEY;
    private static final String KEY = PayActivity.KEY;
    private static final String VECTOR = PayActivity.VECTOR;

    private static final String RETURN_URL = PayActivity.RETURN_URL;
    private static final String NOTICE_URL = PayActivity.NOTICE_URL;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pay_layout);
        initWidgets();
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        goodsName = bundle.getString("GoodsName");
        goodsPrice = bundle.getString("GoodsPrice");
        initData();
        initView();
        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        mPayUtil = new PayUtil(SingleStepPayActivity.this, SingleStepPayActivity.this, true);
        mPayUtil.setPayParam(APPID, KEY, VECTOR, SYSTEM_NAME);
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setContentView(R.layout.pay_layout);
        initView();
    }
    private void initData() {
        mPayTypeModelList = new ArrayList<PayTypeModel>();
        mPayTypeModelList.add(new PayTypeModel("微信", 3, "微信"));
        mPayTypeModelList.add(new PayTypeModel("支付宝", 4, "支付宝"));
        mPayTypeModelList.add(new PayTypeModel("QQ", 11, "QQ支付"));
        mPayTypeModelList.add(new PayTypeModel("京东", 12, "京东支付"));
        mAdapter = new PayTypeRecycleAdapter(mPayTypeModelList);
    }

    private void initView() {
        initWidgets();
        setView();
        mPayName.setText(goodsName);
        mPayPrice.setText(String.format("%s元", goodsPrice));
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mPayUtil != null) {
            mPayUtil.getPayStatus(new PayGetPayStatusListener() {
                @Override
                public void onPayStatus(int payStatus) {
                    if (payStatus == 1) {
                        showToast(getString(R.string.pay_success));
                    } else {
                        showToast(getString(R.string.pay_failure));
                    }
                }
            });
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismiss();
    }

    private TokenParam getTokenParam() {
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String CompKey = COM_KEY;

        String p1_usercode = CODE;
        String p2_order = dateFormat.format(date);
        String p3_money = goodsPrice;
        String p4_returnurl = RETURN_URL; // user define
        String p5_notifyurl = NOTICE_URL; // user define
        String p6_ordertime = dateFormat.format(date);
        String p7_sign = PayMD5Util.getMD5(
                p1_usercode + "&" + p2_order + "&" + p3_money + "&"
                        + p4_returnurl + "&" + p5_notifyurl + "&"
                        + p6_ordertime + CompKey).toUpperCase();

        TokenParam tokenParam = new TokenParam();
        tokenParam.setP1_usercode(p1_usercode);
        tokenParam.setP2_order(p2_order);
        tokenParam.setP3_money(p3_money);
        tokenParam.setP4_returnurl(p4_returnurl);
        tokenParam.setP5_notifyurl(p5_notifyurl);
        tokenParam.setP6_ordertime(p6_ordertime);
        tokenParam.setP7_sign(p7_sign);
        return tokenParam;
    }

    private void initWidgets() {
        mPayName = (TextView) findViewById(R.id.junpay_TextView_name);
        mPayPrice = (TextView) findViewById(R.id.junpay_TextView_price);
        mPayRecycleView = (RecyclerView) findViewById(R.id.junpay_listview);
        GridLayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), isPortrait() ? 1 : 2);
        mPayRecycleView.setLayoutManager(layoutManager);
        if (!isPortrait()) {
            mPayRecycleView.addItemDecoration(mItemDecoration);
        }
        findViewById(R.id.junpay_button_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProgressDialog = ProgressDialog.show(SingleStepPayActivity.this, "", getString(R.string.pay_info), false, true, null);
                int typeId = mPayTypeModelList.get(mCheckedId).getTypeid();
                mPayUtil.getToken(getTokenParam(), typeId);
            }
        });
    }

    private void setView() {
        mAdapter.isPortrait(isPortrait());
        if (mCheckedId == -1) {
            for (PayTypeModel typeModel : mPayTypeModelList) {
                if (typeModel.getTypeid() == 4) {
                    mCheckedId = mPayTypeModelList.indexOf(typeModel);
                    break;
                } else {
                    mCheckedId = 0;
                }
            }
        }
        mAdapter.selectItem(mCheckedId);
        mPayRecycleView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new PayTypeRecycleAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                mCheckedId = position;
                mAdapter.selectItem(mCheckedId);
            }
        });
    }

    private boolean isPortrait() {
        return getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    private void dismiss() {
        if (null != mProgressDialog && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void showToast(final String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mToast.setText(str);
                mToast.show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (null != mPayUtil) {
            mPayUtil.destroy();
        }
        super.onDestroy();
    }

    @Override
    public void onPayException(String exceptionMessage) {
        dismiss();
    }
}
